package com.suning.sawp.service.util;

import java.net.URLDecoder;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mongodb.util.Base64Codec;

/**
 * 加减密 AES算法
 * 
 * @author 14043094
 */
public abstract class AESUtils {
	/**
	 * 初始化日志
	 */
	private static final Logger LOGGER = LoggerFactory.getLogger(AESUtils.class);

	/**
	 * 加解密算法
	 */
	private static final String ALGORITHM = "AES";

	private static final String CIPHER = "AES/CBC/PKCS5Padding";

	private static final String IVPARAMETERSPEC = "0102030405060708";

	private static Base64Codec base64Codec = new Base64Codec();

	/**
	 * 加密
	 * 
	 * @param sSrc
	 *            加密字符串
	 * @return 加密后字符串
	 */
	public static String encrypt(String sSrc, String key) {
		byte[] raw = key.getBytes();
		SecretKeySpec skeySpec = new SecretKeySpec(raw, ALGORITHM);
		Cipher cipher;
		try {
			cipher = Cipher.getInstance(CIPHER);
			IvParameterSpec iv = new IvParameterSpec(IVPARAMETERSPEC.getBytes());// 使用CBC模式，需要一个向量iv，可增加加密算法的强度
			cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
			byte[] encrypted;
			encrypted = cipher.doFinal(sSrc.getBytes());
			return base64Codec.encode(encrypted);// 此处使用BASE64做转码功能，同时能起到2次加密的作用。
		} catch (Exception e) {
			LOGGER.error("Encrypt find wrong!", e);
		}
		return null;
	}

	/**
	 * 解密
	 * 
	 * @param sSrc
	 *            解密字符串
	 * @return 解密后字符串
	 */
	public static String decrypt(String sSrc, String key) {
		try {
			byte[] raw = key.getBytes("ASCII");
			SecretKeySpec skeySpec = new SecretKeySpec(raw, ALGORITHM);
			Cipher cipher = Cipher.getInstance(CIPHER);
			IvParameterSpec iv = new IvParameterSpec(IVPARAMETERSPEC.getBytes());
			cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
			byte[] encrypted1 = base64Codec.decode(sSrc);// 先用base64解密
			byte[] original = cipher.doFinal(encrypted1);
			String originalString = new String(original);
			return originalString;
		} catch (Exception ex) {
			LOGGER.error("Decrypt find wrong! sSrc = " + sSrc, ex);
			return null;
		}
	}

	/**
	 * 
	 * 功能描述: 先URL解码再解密<br>
	 * 〈功能详细描述〉
	 *
	 * @param sSrc
	 * @param key
	 * @return
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	public static String decodeAndDecrypt(String sSrc, String key) {
		try {
			if (StringUtils.isNotBlank(sSrc)) {
				String decodeSsrc = URLDecoder.decode(sSrc, "UTF-8");
				return decrypt(decodeSsrc, key);
			} else {
				return null;
			}
		} catch (Exception e) {
			LOGGER.error("decodeAndDecrypt find wrong! sSrc = " + sSrc, e);
			return null;
		}
	}

}